package ru.housewife.service.wares;

import org.hibernate.Query;
import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.cache.CacheManager;
import ru.housewife.form.WareForm;
import ru.housewife.model.Ware;
import ru.housewife.model.WaresGroup;

import java.util.List;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
public class AddNewWare implements HibernateAction<Boolean> {

    private CacheManager cacheManager = CacheManager.getInstance();

    private WareForm wareForm;

    public AddNewWare(WareForm wareForm) {
        this.wareForm = wareForm;
    }

    @Override
    public Boolean execute(Session session) {
        Query q = session.createQuery("select w from Ware w where lower(w.name) = :name");
        q.setString("name", wareForm.getName().toLowerCase());
        List lst = q.list();
        if (lst != null && lst.size() > 0) {
            return false;
        }

        WaresGroup group = (WaresGroup) session.get(WaresGroup.class, wareForm.getGroupForm().getId());
        if (group == null) {
            return false;
        }
        
        Ware ware = new Ware();
        ware.setName(wareForm.getName());
        ware.setMeasure(wareForm.getMeasure());
        ware.setWaresGroup(group);

        session.save(ware);
        wareForm.setId(ware.getId());

        cacheManager.putWareForm(wareForm);

        return true;
    }
}
